/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */
#include "Sun.h"

namespace PQEngine
{
	const Ogre::String Sun::ENTITY_NAME = "Env/Sun/Entity";
	const Ogre::String Sun::MESH_NAME = "Env/Sun/Mesh";
    const Ogre::String Sun::MATERIAL_NAME = "Env/Sun/Material";
	const Ogre::String Sun::MATERIAL_CLONE_NAME = "Env/Sun/MaterialClone";
	const Ogre::String Sun::TEXTURE_NAME = "Env/Sun/Texture";
	const Ogre::String Sun::BILLBOARD_NAME = "Env/Sun/Billboard";

	Sun::Sun(SceneObject* sceneObject)
		: SkyLight(sceneObject),_sunTextureAngularSize(Ogre::Degree(3.77f)),_enabled(true)
	{
		//init the material
		initMaterial();
		initBillboards();
		
	}

	void Sun::initMaterial()
	{
		Ogre::MaterialPtr ptr=Ogre::MaterialManager::getSingletonPtr()->getByName(MATERIAL_NAME);
		if(ptr.isNull()){
			return;
		}
		//clone
		_material=ptr->clone(MATERIAL_CLONE_NAME);
		_material->load();
	}

	void Sun::initBillboards()
	{
		Ogre::SceneManager* sceneManager=_sceneObject->getSceneManager();
		_billboards= sceneManager->createBillboardSet(BILLBOARD_NAME+Ogre::StringConverter::toString(getId()));

		_billboards->setMaterialName(_material->getName());
		_billboards->setCastShadows(false);
		_billboards->setRenderQueueGroup(SCENE_RENDER_QUEUE_SUN);
		_billboards->setDefaultDimensions(1.0f,1.0f);
		_billboards->createBillboard(Ogre::Vector3::ZERO);

		_sceneNode->attachObject(_billboards);
		_sceneNode->setInheritOrientation(false);
	}



	void Sun::update(const Ogre::Vector3& direction,const Ogre::ColourValue &lightColor,const Ogre::ColourValue &bodyColor)
	{
		if(!_enabled){
			return;
		}

		SkyLight::update(direction,lightColor,bodyColor);

		 // Set sun position.
        Ogre::Real sunDistance = _radius - _radius * Ogre::Math::Tan(_sunTextureAngularSize);
		_sceneNode->setPosition(-direction*sunDistance);

        // Set sun scaling in [1.0 ~ 1.2] range
        float factor = 1.2f - _bodyColor.b * 0.2f;
        float scale = factor * sunDistance * Ogre::Math::Tan(_sunTextureAngularSize);
		_sceneNode->setScale(Ogre::Vector3::UNIT_SCALE * scale);

	}

	 void Sun::setSunTextureAngularSize(const Ogre::Degree& sunTextureAngularSize)
	 {
        _sunTextureAngularSize = sunTextureAngularSize;
	 }

}
